/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import com.sshtools.j2ssh.*;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;
import com.sshtools.j2ssh.connection.Channel;
import com.sshtools.j2ssh.connection.ChannelEventAdapter;
import com.sshtools.j2ssh.connection.ChannelEventListener;
import com.sshtools.j2ssh.session.SessionChannelClient;
import com.sshtools.j2ssh.transport.IgnoreHostKeyVerification;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
 *
 * @author ARIJIT PAL
 */
public class SSHClient {

    private SshClient ssh;
    public SSHClient(){
        ssh = new SshClient();
    }
    public boolean openConnection(String host, int port, String userName, String password){
        try {
            ssh.connect(host, port, new IgnoreHostKeyVerification());
            //Authenticate
            PasswordAuthenticationClient passwordAuthenticationClient = new PasswordAuthenticationClient();
            passwordAuthenticationClient.setUsername(userName);
            passwordAuthenticationClient.setPassword(password);
            int result = ssh.authenticate(passwordAuthenticationClient);
            if (result != AuthenticationProtocolState.COMPLETE) {
                System.out.println("Failed");
                return false;
            }
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }
    public boolean closeConnection(){
        ssh.disconnect();
        return true;
    }
    public String executeCommand(String cmd) {
        if (ssh.isConnected()) {
            try {
                String output = "";
                SessionChannelClient session = ssh.openSessionChannel();
                InputStream in = session.getInputStream(); // start input stream for ssh result
                BufferedReader br = new BufferedReader(new InputStreamReader(in)); // read to buffer from the stream
                StringBuilder buffer = new StringBuilder();
                System.out.println("Starting to execute commands: " + cmd);
                session.executeCommand(cmd);  // execute the command via SSH session
                String line = "";
                while (((line = br.readLine()) != null)) // read from the buffer of the stream the line
                {
                    buffer.append(line); // append the result line to the String buffer.
                    buffer.append("\n");
                }
                output = buffer.toString();  // Convert the output line from stringbuffer to String.
                session.close();  // close the SSH session.
                return output;
            } catch (Exception ex) {
                ex.printStackTrace();
                return null;
            }
        } else {
            return null;
        }
    }

    public boolean getFile(String remotePath, String localPath) {
        if (ssh.isConnected()) {
            try {
                /*ScpClient client = ssh.openScpClient();

                client.get(localPath, remotePath, true);
                return true;*/

                SessionChannelClient session = ssh.openSessionChannel();
                File file = new File(localPath);
                FileOutputStream fos = new FileOutputStream(file);
                InputStream in = session.getInputStream(); // start input stream for ssh result
                //BufferedReader br = new BufferedReader(new InputStreamReader(in)); // read to buffer from the stream
                //StringBuilder buffer = new StringBuilder();
                //System.out.println("Starting to execute commands: " + cmd);
                session.executeCommand("scp -f "+remotePath);  // execute the command via SSH session
                while(in.available()>0){
                    fos.write(in.read());
                }
                session.close();  // close the SSH session.
                return true;
            } catch (Exception ex) {
                ex.printStackTrace();
                return false;
            }
        } else {
            return false;
        }
    }

    public boolean putFile(String localPath, String remotePath) {
        if (ssh.isConnected()) {
            try {
                ScpClient client = ssh.openScpClient();
                client.put(localPath, remotePath, true);
                return true;
            } catch (Exception ex) {
                ex.printStackTrace();
                return false;
            }
        } else {
            return false;
        }
    }

    public static void main(String[] args)throws Exception{
        SSHClient object = new SSHClient();
        //object.openConnection("shellmix.com", 22, "arijitpal", "pa00word");
        object.openConnection("localhost", 22, "sshuser", "test123");
        //System.out.println(object.executeCommand("ls -l"));
        object.getFile("test.zip", "D:\\test.zip");
        object.closeConnection();
    }
}
